import React, { useEffect, useRef, useState, RefObject } from 'react';
import ReactDOM from 'react-dom';

/**
 *
 * @param initVisible
 * @param excludeRef 要排除的结点，类型ref
 * @returns
 */
export const useClickOutside = (initVisible = false, excludeRef: any = null) => {
  const [visible, setVisible] = useState(initVisible);
  const ref = useRef(null);

  const bindClickEventToWindow = () => {
    const clickHandler = (e: any) => {
      if (ref.current && ReactDOM && !ReactDOM.findDOMNode(ref.current)?.contains(e.target)) {
        if (excludeRef?.current && ReactDOM.findDOMNode(excludeRef.current)?.contains(e.target)) {
          return;
        } else {
          setVisible(false);
        }
      }
    };

    window.addEventListener('click', clickHandler);
    return (): void => {
      window.removeEventListener('click', clickHandler);
    };
  };

  useEffect(() => {
    bindClickEventToWindow();
  }, []);

  return {
    visible,
    setVisible,
    ref
  };
};
